﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EasyBlog.Data;
using EasyBlog.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace EasyBlog.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BlogApi2Controller : ControllerBase
    {
        private readonly static Dictionary<string, string> DTokenUserName = new Dictionary<string, string>();
        private readonly DbXlp db;
        private string UserName { get; set; }
        public BlogApi2Controller(DbXlp context)
        {
            db = context;
        }

        [HttpGet]
        public ResponseItem Get(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                return new ResponseItem { Code = false, Message = "用户名和密码不能为空" };
            var item = db.InfoUsers.Find(userName);
            //if(item!=null && item.Password==password)
            if (item?.Password == password)
            {
                var token = Guid.NewGuid().ToString();
                DTokenUserName.Add(token, userName);
                return new ResponseItem { Content = token };

            }
            else
                return new ResponseItem { Code = false, Message = "密码错误" };

        }
        [HttpPost]
        public ResponseItem Post([FromBody] RequestItem item)
        {
            try
            {
                if (!DTokenUserName.ContainsKey(item.Token))
                    return new ResponseItem { Code = false, Message = "Token不存在" };
                UserName = DTokenUserName[item.Token];
                object retval;
                switch (item.MethodName)
                {
                    case "GetList":
                        retval = GetList(item.Content);
                        break;
                    case "Add":
                        retval = Add(item.Content);
                        break;
                    default:
                        return new ResponseItem { Code = false, Message = "不认识的方法" };
                }
                return new ResponseItem { Content = JsonConvert.SerializeObject(retval) };

            }
            catch (Exception ex)
            {
                return new ResponseItem { Code = false, Message = ex.Message };
            }
        }
     

        private object GetList(string q)
        {
            return db.InfoBlogs.Where(ii => ii.UserName == UserName).ToList();
        }

        private object Add(string q)
        {
            var item = JsonConvert.DeserializeObject<InfoBlog>(q);

            item.UserName = UserName;
            //InfoBlog item = new InfoBlog { UserName = userName, Title = title, Content = content, DTCreate = DateTime.Now, VisitCount = 0 };
            db.InfoBlogs.Add(item);
            db.SaveChanges();
            return true;
        }

    }
}